import json
from functools import wraps

from django.core.paginator import Paginator
from django.http import JsonResponse

# Create your views here.

from apps.message.models import MessageInfo, FileInfo
from apps.user.models import UserInfo


# 检测请求方式装饰器
def check_method(func):
    @wraps(func)
    def is_post(request):
        if request.method != 'POST':
            result = {'code': 401, 'error': '请求方式错误！'}
            return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )
        else:
            # 取出请求的body体并把json格式转为python字典形式
            json_obj = json.loads(request.body)
            return func(request, json_obj)

    return is_post


# 发送消息
def send_activity_message_view(request):
    try:
        json_obj = json.loads(request.POST['data'])
        sender = json_obj['sender']
        receiver = json_obj['receiver']
        message_type = json_obj['message_type']
        message_content = json_obj['message_content']
        message_title = json_obj['message_title']

    except Exception as e:
        print(e)
        result = {'code': 402, 'error': '未获取到数据或数据变量名错误！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )

    try:
        sender_obj = UserInfo.objects.get(user_name=sender)
        receiver_obj = UserInfo.objects.get(id=receiver)
        message_obj = MessageInfo(message_content=message_content, message_title=message_title,
                                  message_type=message_type)
        message_obj.save()
        message_obj.sender.add(sender_obj)
        message_obj.receiver.add(receiver_obj)
        message_obj.save()

        # 判断是不是参加活动的消息
        if message_type == '0' or message_type == '2':
            is_null = json_obj['is_null']
            join_activity_id = json_obj['join_activity_id']
            message_obj.join_activity_id = join_activity_id
            message_obj.save()
            # 如果是活动申请消息需要存储附件
            if not is_null:
                file_list = request.FILES.getlist('file')

                for i in file_list:
                    file_obj = FileInfo(message=message_obj, file_accessory=i)
                    file_obj.save()

        result = {'code': 200, 'success': '消息发送成功！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )
    except Exception as e:
        print(e)
        result = {'code': 403, 'error': '用户不存在！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )


# 获取消息
@check_method
def receive_message_view(request, json_obj):
    try:
        choice_message_type = json_obj['message_type']
        page = json_obj['page']
        user_name = json_obj['user_name']
    except Exception as e:
        print(e)
        result = {'code': 402, 'error': '未获取到数据或数据变量名错误！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )

    try:
        user_obj = UserInfo.objects.get(user_name=user_name)
        # 默认除已删外
        if choice_message_type == 0:
            message_list = user_obj.receiver_message_id.exclude(message_status='2').order_by(
                '-message_create_time').values()
        # 未读消息
        elif choice_message_type == 1:
            message_list = user_obj.receiver_message_id.filter(message_status='0').order_by(
                '-message_create_time').values()
        # 已读消息
        else:
            message_list = user_obj.receiver_message_id.filter(message_status='1').order_by(
                '-message_create_time').values()

        if len(message_list) == 0:
            result = {'code': 403, 'error': '消息为空！'}
            return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )
        elif len(message_list) < 10:
            paginator = Paginator(message_list, len(message_list))
        else:
            paginator = Paginator(message_list, 10)
        page_num = paginator.num_pages
        page_obj = paginator.page(page)

        result = {'code': 200, 'data': list(page_obj.object_list), 'pageNum': page_num}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )
    except Exception as e:
        print(e)
        result = {'code': 403, 'error': '用户不存在！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )


# 点击查看消息
@check_method
def read_message_view(request, json_obj):
    try:
        read_method = json_obj['read_method']
        user_name = json_obj['user_name']
    except Exception as e:
        print(e)
        result = {'code': 402, 'error': '未获取到数据或数据变量名错误！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )

    try:
        if read_method == 0:
            message_id = json_obj['id']
            message_obj = list(MessageInfo.objects.filter(id=message_id))

            message_obj[0].message_status = '1'
            message_obj[0].save()

            if message_obj[0].message_type == '0' or message_obj[0].message_type == '2':
                fileList = list(message_obj[0].file_list_id.all().values())
            else:
                fileList = {'toast': '只读消息!'}

            message_list = list(MessageInfo.objects.filter(id=message_id).values())

            result = {'code': 200,
                      'data': {'senderInfo': list(message_obj[0].sender.all().values()), 'fileList': fileList,
                               'sendInfo': message_list}}
        else:
            message_ids = json_obj['ids']
            print(user_name)

            for i in message_ids:
                message_obj = MessageInfo.objects.get(id=i['id'])
                message_obj.message_status = '1'
                message_obj.save()
            result = {'code': 200}

        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )
    except Exception as e:
        print(e)
        result = {'code': 403, 'error': '消息不存在！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )


# 删除消息
@check_method
def delete_message_view(request, json_obj):
    try:
        delete_method = json_obj['delete_method']
    except Exception as e:
        print(e)
        result = {'code': 402, 'error': '未获取到数据或数据变量名错误！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )

    try:
        if delete_method == 0:
            message_id = json_obj['id']

            message_obj = MessageInfo.objects.get(id=message_id)

            message_obj.message_status = '2'
            message_obj.save()
        else:
            message_ids = json_obj['ids']

            for i in message_ids:
                message_obj = MessageInfo.objects.get(id=i['id'])
                message_obj.message_status = '2'
                message_obj.save()

        result = {'code': 200}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )
    except Exception as e:
        print(e)
        result = {'code': 403, 'error': '消息不存在！'}
        return JsonResponse(result, json_dumps_params={"ensure_ascii": False}, )
